<template>
	<view class="map_content">
		<view class="page-body">
			<view class="page-section page-section-gap map">
				<map @tap="getMapLocation" style="width: 100%; height: 500rpx" :latitude="reportInfo.lttd" :longitude="reportInfo.lgtd" :markers="covers"></map>
			</view>
			<view class="item">
				<view class="text-black margin-top-sm overflow-2 item-title">
					<text class="cuIcon-location text-green text-xxl"></text>
					您当前所在位置:
					<text class="text-green">{{ plot.rough }}</text>
				</view>
				<view class="text-black text-sm margin-top-sm overflow-2 item-content">系统已为您匹配到智能垃圾桶</view>
				<view class="item-content">
					编号:
					<text class="text-red">JN00405</text>
					<text style="margin-left: 120rpx">距您:</text>
					<text class="text-red">{{ distance }}</text>
					KM
				</view>
				<view class="uni-button-group">
					<button class="uni-button" @click="markertap" :styles="{ borderColor: '#678D5D' }">导航</button>
				</view>
			</view>
			<view class="m-footer">
				<button class="img-footer" @click="showRules">点我了解丢垃圾规则</button>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import QQMapWX from '@/utils/qqmap-wx-jssdk.js';
const content = ref(
	'（一）将回收价值高的可回收物率先分类投放，如报纸杂志、纸板箱、包装盒、PET塑料瓶、易拉罐等，确保这一类可回收物不被混合垃圾污染。（二）不要将已被污染、潮湿、污渍无法清除的物品投入可回收物收集容器，如被油渍污染的餐盒、食品包装盒等。瓶罐投放前倒空瓶内液体并简单清洗，有瓶盖的不需将瓶盖与瓶体分开投放，确保可回收物收集容器中的其他废品不被污染，尊重和维护他人分类的成果。（三）不确定是否可以回收（或本指引中未明确说明）的废纸、废塑料，在未被污染的情况下，请先投放至可回收物收集容器'
);
const reportInfo = ref({
	lgtd: 116.39742,
	lttd: 39.909
});
const id = ref(0);
const title = ref('map');
const latitude = ref(39.909);
const longitude = ref(116.39742);
const covers = ref([]);
const isLocated = ref(false);
const plot = ref({});
const address = ref('');
const addressComponent = ref({
	city: '',
	district: '',
	nation: '',
	province: '',
	street: '',
	street_number: ''
});
const distance = ref(0.1);
const showRules = () => {
	uni.showModal({
		title: '请阅读以下规则',
		content: content.value,
		showCancel: false,
		confirmText: '我已了解',
		success: function (res) {}
	});
};
const getLocation = () => {
	uni.getLocation({
		type: 'gcj02', // 'wgs84'默认gps 坐标 'gcj02'国测
		altitude: false, // 是否返回高度
		accuracy: 'best', // 精度值为20m
		geocode: true,
		success: (res) => {
			console.log(res);
			successCb && successCb(res);
			isLocated.value = true;
			//获取经纬度
			reportInfo.value.lttd = res.latitude;
			reportInfo.value.lgtd = res.longitude;
			//标记地点
			var obj = {
				width: 30,
				height: 30,
				latitude: Number(reportInfo.value.lttd),
				longitude: Number(reportInfo.value.lgtd),
				iconPath: '../../static/icons/标记,定位,标点.png'
			};
			//垃圾桶
			var bin = {
				id: '0',
				latitude: Number(30.89204),
				longitude: Number(120.086678),
				width: 20,
				height: 20,
				iconPath: '../../static/icons/垃圾桶.png',
				title: '垃圾桶'
			};
			var bin2 = {
				id: '1',
				latitude: Number(32.097269),
				longitude: Number(118.91422),
				width: 20,
				height: 20,
				iconPath: '../../static/icons/垃圾桶.png',
				title: '垃圾桶'
			};
			// distance.value = self.getMapDistance(self.reportInfo.lttd, self.reportInfo.lgtd, 32.097269, 118.91422);
			var arr = [];
			arr.push(obj);
			arr.push(bin);
			arr.push(bin2);
			//标记点
			covers.value = arr;
		},
		fail(err) {
			if (err.errMsg === 'getLocation:fail 频繁调用会增加电量损耗，可考虑使用 wx.onLocationChange 监听地理位置变化') {
				uni.showToast({
					title: '请勿频繁定位',
					icon: 'none'
				});
			}
			if (err.errMsg === 'getLocation:fail auth deny') {
				// 未授权
				uni.showToast({
					title: '无法定位，请重新获取位置信息',
					icon: 'none'
				});
				authDenyCb && authDenyCb();
				isLocated.value = false;
			}
			if (err.errMsg === 'getLocation:fail:ERROR_NOCELL&WIFI_LOCATIONSWITCHOFF') {
				uni.showModal({
					content: '请开启手机定位服务',
					showCancel: false
				});
			}
		},
		complete() {
			console.log(reportInfo.value);
			tMap.reverseGeocoder({
				location: {
					latitude: reportInfo.value.lttd,
					longitude: reportInfo.value.lgtd
				},
				success: function (res) {
					console.log('解析地址成功');
					console.log(res);
					plot.value = res.result.formatted_addresses;
					address.value = res.result.address;
					addressComponent.value = res.result.address_component;
					// 省
					// let province = res.result.ad_info.province;
					// 市
					let city = res.result.ad_info.city;
					// console.log(province);
				},
				fail: function (res) {
					uni.showToast({
						title: '定位失败',
						duration: 2000,
						icon: 'none'
					});
					console.log(res);
				},
				complete: function (res) {
					//无论成功失败都会执行
					console.log(res);
				}
			});
		}
	});
};
const getAuthorize = (successCb, authDenyCb) => {
	uni.authorize({
		scope: 'scope.userLocation',
		success: () => {
			getLocation(successCb, authDenyCb);
		},
		fail: (err) => {
			err = err['errMsg'];
			uni.showModal({
				content: '需要授权位置信息',
				confirmText: '确认授权'
			}).then((res) => {
				if (res[1]['confirm']) {
					uni.openSetting({
						success: (res) => {
							if (res.authSetting['scope.userLocation']) {
								// 授权成功
								uni.showToast({
									title: '授权成功',
									icon: 'none'
								});
							} else {
								// 未授权
								uni.showToast({
									title: '授权失败',
									icon: 'none'
								});
							}
							getLocation(successCb, authDenyCb);
						}
					});
				}
				if (res[1]['cancel']) {
					// 取消授权
					console.log('取消');
					getLocation(successCb, authDenyCb);
				}
			});
		}
	});
};
const getMapLocation = () => {
	uni.chooseLocation({
		success: (res) => {
			console.log(res);
			reportInfo.value.lttd = res.latitude;
			reportInfo.value.lgtd = res.longitude;
			var obj = {
				width: 30,
				height: 30,
				latitude: reportInfo.value.lttd,
				longitude: reportInfo.value.lgtd,
				iconPath: '@/static/icons/标记,定位,标点.png'
			};
			var arr = [];
			arr.push(obj);
			covers.value = arr;
			console.log(covers.value, 'covers');
		},
		complete() {
			console.log(reportInfo.value);
			tMap.reverseGeocoder({
				location: {
					latitude: reportInfo.value.lttd,
					longitude: reportInfo.value.lgtd
				},
				success: function (res) {
					console.log('解析地址成功');
					console.log(res);
					plot.value = res.result.formatted_addresses;
					address.value = res.result.address;
					addressComponent.value = res.result.address_component;
					// 省
					// let province = res.result.ad_info.province;
					// 市
					let city = res.result.ad_info.city;
					// console.log(province);
				},
				fail: function (res) {
					uni.showToast({
						title: '定位失败',
						duration: 2000,
						icon: 'none'
					});
					console.log(res);
				},
				complete: function (res) {
					//无论成功失败都会执行
					console.log(res);
				}
			});
		}
	});
};
const markertap = () => {
	uni.getLocation({
		success: (res) => {
			uni.openLocation({
				latitude: Number(30.89204),
				longitude: Number(120.086678),
				name: 'JN00405号垃圾桶',
				address: '垃圾桶',
				success: () => {
					console.log('success');
				},
				fail: () => {
					uni.showModal({
						title: '错误',
						content: '请检查定位是否打开',
						showCancel: false,
						success: function (res) {
							if (res.confirm) {
								console.log('用户点击确定');
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				}
			});
		}
	});
};
const Rad = (d) => {
	return (d * Math.PI) / 180.0; //经纬度转换成三角函数中度分表形式。
};
const getMapDistance = (lat1, lng1, lat2, lng2) => {
	console.log('in getMap');
	console.log(lat1);
	var radLat1 = Rad(lat1);
	var radLat2 = Rad(lat2);
	var a = radLat1 - radLat2;
	var b = Rad(lng1) - Rad(lng2);
	var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
	s = s * 6378.137; // EARTH_RADIUS;
	s = Math.round(s * 10000) / 10000; //输出为公里
	//s=s.toFixed(2);
	return s;
};
onLoad(() => {
	getAuthorize();
});
var qqmapsdk = new QQMapWX({
	key: 'H3BBZ-L2BK3-A4C3Z-OEMVS-Y54TJ-HKFFP' // 必填
});
</script>
<style lang="scss" scoped>
.map_content {
	width: 100%;
	height: 100vh;
	box-sizing: border-box;
	padding: 20rpx 20rpx;
	.page-body {
		height: 100%;
		.map {
			border: 2rpx solid #678d5d;
		}
		.item {
			height: 400rpx;
			box-sizing: border-box;
			padding: 20rpx 20rpx;
			margin-top: 80rpx;
			border: 4px solid #9e9e9e;
			border-radius: 25rpx;
			font-weight: 700;
			.item-content {
				height: 80rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 34rpx;
			}
			.uni-button-group {
				/* #ifndef APP-NVUE */
				height: 150rpx;
				display: flex;
				/* #endif */
				justify-content: center;
				align-items: center;
			}
			.uni-button {
				width: 300rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 14px;
				border-radius: 12px;
				margin: 0;
				background-color: #678d5d;
				color: white;
			}
		}
		.m-footer {
			height: 400rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			.img-footer {
				border: none;
				border-radius: 12px;
				background-color: #006eff;
				display: flex;
				align-items: center;
				justify-content: center;
				color: #fff;
				margin: 0;
			}
		}
	}
}
</style>
